package cn.jtool.dig.server.comm.tunnel.protocol;

import cn.jtool.dig.common.model.*;
import cn.jtool.dig.common.netty.CtxUtils;
import cn.jtool.dig.common.netty.ProtocolProcess;
import cn.jtool.dig.common.netty.SNGenerator;
import cn.jtool.dig.common.netty.SessionManager;
import cn.jtool.dig.server.comm.VirtualChannelManager;
import cn.jtool.dig.server.comm.tunnel.TunnelAttrKey;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 关闭链路请求
 */
@Slf4j
@Component
public class P_12_CloseSession implements ProtocolProcess {

    @Override
    public int protocolId() {
        return Commands.CLOSE_SESSION.getCode();
    }

    @Override
    public Packet process(ChannelHandlerContext ctx, Packet packet) {
        PacketHeader header = packet.getHeader();
        Long channelId = header.getChannelId();
        Long sessionId = CtxUtils.getAttribute(ctx, TunnelAttrKey.SESSION_ID);
        log.info("关闭链路请求, channelId: {}", header.getChannelId());
        //通道为0,则关闭所有链路
        if(Objects.isNull(channelId) || channelId == 0){
            List<Session> sessionList = SessionManager.getSession().stream().filter(e -> e.getLicenseId() == sessionId.intValue()).collect(Collectors.toList());
            if(CollectionUtils.isNotEmpty(sessionList)){
                sessionList.forEach(e->this.closeSession(e.getId()));
            }
        }else{
            this.closeSession(channelId);
        }
        return this.outpacket(packet);
    }

    private void closeSession(long channelId){
        VirtualChannelManager.removeVirtualChannel(channelId);
        Session session = SessionManager.getSession(channelId);
        if(Objects.nonNull(session)){
            if(Objects.nonNull(session.getChannelHandlerContext()) && session.getChannelHandlerContext().channel().isOpen()){
                session.disconnect();
            }
//            SessionManager.removeSession(channelId);
        }
    }

    private Packet outpacket(Packet inpacket){
        PacketHeader outheader = new PacketHeader();
        outheader.setCommand(Commands.COMMON_RESPONSE.getCode());
        outheader.setDigId(inpacket.getHeader().getDigId());
        outheader.setChannelId(inpacket.getHeader().getChannelId());
        outheader.setSn(SNGenerator.gen());
        PacketBody outbody = new PacketBody();
        outbody.writeByte(inpacket.getHeader().getCommand());
        outbody.writeWord(inpacket.getHeader().getSn());
        outbody.writeByte(0x00);
        return Packet.builder().header(outheader).body(outbody).build();
    }
}
